package cn.enjoyedu.producerconfirm;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发送者消息可靠性，发送确认模式 单条确认 生产者发送一条到rabbitMQ的队列 rabbitMQ确认一条
 * 启用发送者确认模式 channel.confirmSelect();
 * 确认成功：channel.waitForConfirms()
 */
public class ProducerConfirm {

    public final static String EXCHANGE_NAME = "producer_confirm";
    private final static String ROUTE_KEY = "error";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        /**
         * 创建连接连接到RabbitMQ
         */
        ConnectionFactory factory = new ConnectionFactory();
        // 设置MabbitMQ所在主机ip或者主机名
        factory.setHost("127.0.0.1");
        // 创建一个连接
        Connection connection = factory.newConnection();
        // 创建一个信道
        Channel channel = connection.createChannel();
        // 指定转发
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        channel.addReturnListener((replyCode, replyText, exchange, routingKey, properties, body) -> {
            String message = new String(body);
            System.out.println("RabbitMq返回的replyCode:  " + replyCode);
            System.out.println("RabbitMq返回的replyText:  " + replyText);
            System.out.println("RabbitMq返回的exchange:  " + exchange);
            System.out.println("RabbitMq返回的routingKey:  " + routingKey);
            System.out.println("RabbitMq返回的message:  " + message);
        });
        // 启用发送者确认模式
        channel.confirmSelect();

        //所有日志严重性级别
        for(int i=0;i<2;i++){
            // 发送的消息
            String message = "Hello World_"+(i+1);
            //参数1：exchange name
            //参数2：routing key
            channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY, true,null, message.getBytes());
            System.out.println(" Sent Message: [" + ROUTE_KEY +"]:'"+ message + "'");
            if (channel.waitForConfirms()) {
                //确认成功
                System.out.println("send success");
            } else {
                System.out.println("send failure");
            }
        }
        // 关闭频道和连接
        channel.close();
        connection.close();
    }

}
